package com.lian.community.interceptor;

import com.lian.community.dao.redis.JedisDAO;
import com.lian.community.dao.user.UserDAO;
import com.lian.community.dao.user.po.UserPO;
import com.lian.community.entity.user.HostUser;
import com.lian.community.entity.user.User;
import com.lian.community.service.token.TokenService;
import com.lian.community.util.SaltUtil;
import jdk.nashorn.internal.parser.Token;
import org.apache.catalina.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TokenAuthInteceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;
    @Autowired
    HostUser hostUser;
    @Autowired
    UserDAO userDAO;
    @Autowired
    JedisDAO jedisDAO;

    public static final String[] REQUIRE_NOT_AUTH_URLS = new String[]{
            "/login", "/reg",  "/index","/reLogin", "/doLogin","/loginAndPersistence"
    };

    public boolean containUrls(String url){
        for (String getUrl : REQUIRE_NOT_AUTH_URLS ) {
            if(getUrl.equals(url)){
                return true;
            }
        }
        return false;
    }
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String url = httpServletRequest.getRequestURI();
        if(containUrls(url)){
            return true;
        }
        Cookie[] cookies = httpServletRequest.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    String getToken = (String) httpServletRequest.getSession().getAttribute("token");
                    System.out.println(getToken);
                    if(getToken != null && getToken.equals(cookie.getValue()) || tokenService.containsToken(cookie.getValue())){
                        return true;
                    }
                }
            }
        }
        httpServletResponse.sendRedirect("/reLogin?next=" + httpServletRequest.getRequestURI());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        return;
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        return;
    }
}
